package com.lin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lin.entity.Menu;
import com.lin.entity.Role;
import com.lin.entity.RoleMenu;
import com.lin.entity.User;
import com.lin.exception.BusinessException;
import com.lin.jwt.JWTToken;
import com.lin.mapper.MenuMapper;
import com.lin.mapper.RoleMenuMapper;
import com.lin.mapper.UserMapper;
import com.lin.reponse.ResultCode;
import com.lin.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.utils.JWTUtils;
import com.lin.utils.MD5Utils;
import com.lin.vo.UserVO;
import org.apache.http.auth.AUTH;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Lin
 * @since 2022-03-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 找到用户页面
     *
     * @param page   页面
     * @param userVO 用户签证官
     * @return {@link IPage}<{@link User}>
     */
    public IPage<User> findUserPage(IPage<User> page, UserVO userVO) {
        List<User> userPage = this.baseMapper.findUserPage(page, userVO);
        page.setRecords(userPage);
        return page;
    }

    @Override
    public void addUser(User user) {}

    /**
     * excel导出用户
     *
     * @param response 响应
     * @param tbUsers  导出的内容
     * @throws IOException IOException
     */
    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> tbUsers) throws IOException {
        //----- 写入excel文件
        String exportFileName = "TbUserInfo.xlsx";
        //响应字符格式
        response.setCharacterEncoding("UTF-8");
        //上下文内容的格式
        response.setContentType("application/vnd.ms-excel");
        //添加请求头的参数
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        //通过流的方式写出文件
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(tbUsers);
    }

    @Override
    public List<User> findUsers(UserVO userVO) {
        List<User> users = this.baseMapper.findUsers(userVO);
        return users;
    }

    @Override
    public String login(String username, String password) {
        String token="";
        User user = this.baseMapper.loadUserByUsername(username);
        if (user!=null){
            //1.需要获取user中的盐
            String salt = user.getSalt();
            //2.对原密码进行加密加盐的处理
            String encryption = MD5Utils.md5Encryption(password, salt);
            //3.对加密后的密码跟数据库中的匹配
            if(encryption.equals(user.getPassword())) {
                token = JWTUtils.sign(username, encryption);
                JWTToken jwtToken=new JWTToken(token);
                try {
                    SecurityUtils.getSubject().login(jwtToken);
                }catch (AuthenticationException e){
                    throw new BusinessException(ResultCode.NO_PERMISSION.getCode(), ResultCode.NO_PERMISSION.getMessage());
                }

            }else {
            //    USER_CREDENTIALS_ERROR
                throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR.getCode(),
                        ResultCode.USER_CREDENTIALS_ERROR.getMessage());
            }
        }else {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        return token;
    }

    @Override
    public boolean upd(String username, String password) {
        User user = this.baseMapper.selectById(5);
        String salt = user.getSalt();
        String encryption = MD5Utils.md5Encryption(password, salt);
        user.setPassword(encryption);
        boolean b = this.updateById(user);
        return b;
    }

    @Override
    public User loadUserByUsername(String username) {
        return this.baseMapper.loadUserByUsername(username);
    }

    @Override
    public List<Role> findRolesById(Long id) {
        return this.baseMapper.findRolesById(id);
    }

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> findMenuByRoles(List<Role> roles) {
        List<Menu> menus=new ArrayList<>();
        if(!CollectionUtils.isEmpty(roles)){
            Set<Long> menuIds=new HashSet<>();//存放用户的菜单id
            List<RoleMenu> roleMenus;
            for (Role role : roles) {
                //根据角色的id获取userRole中间表的菜单id
                roleMenus= roleMenuMapper.selectByRoleId(role.getId());
                if(!CollectionUtils.isEmpty(roleMenus)){
                    for (RoleMenu roleMenu : roleMenus) {
                        menuIds.add(roleMenu.getMenuId());
                    }
                }
            }
            if(!CollectionUtils.isEmpty(menuIds)){
                for (Long menuId : menuIds) {
                    //该用户所有的菜单
                    Menu menu = menuMapper.selectByPrimaryKey(menuId);
                    if(menu!=null){
                        menus.add(menu);
                    }
                }
            }
        }
        return menus;
    }


}

